package redis

import (
	"time"

	"github.com/garyburd/redigo/redis"
)

// redisPool redis连接池
var redisPool redis.Pool

// Conn redis连接
type Conn struct {
	Conn redis.Conn
}

// NewPool 初始化一个连接池
func NewPool(host string, password string, active int, idle int) {
	redisPool = redis.Pool{
		MaxActive: active,
		MaxIdle:   idle,
		Dial: func() (redis.Conn, error) {
			c, err := redis.DialTimeout("tcp", host, time.Duration(5)*time.Second, time.Duration(5)*time.Second, time.Duration(5)*time.Second)
			if err != nil {
				panic(err)
			}
			if password != "" {
				_, err = c.Do("AUTH", password)
				if err != nil {
					panic(err)
				}
			}
			return c, err
		},
	}
}

// Close 关闭连接池
func Close() {
	redisPool.Close()
}

// GetConn 从连接池取得一个连接
func GetConn() *Conn {
	return &Conn{Conn: redisPool.Get()}
}

// Close 连接池回收连接
func (db *Conn) Close() {
	db.Conn.Close()
}

// EXPIRE 设置key的有效期
func (db *Conn) EXPIRE(key string, seconds int) error {
	_, err := db.Conn.Do("EXPIRE", key, seconds)

	return err
}

// DEL 删除一个key
func (db *Conn) DEL(key string) error {
	_, err := db.Conn.Do("DEL", key)
	return err
}

// EXISTS 检查一个建是否存在
func (db *Conn) EXISTS(key string) (bool, error) {
	exists, err := redis.Bool(db.Conn.Do("EXISTS", key))
	if err != nil {
		return false, err
	}
	return exists, nil
}
